package it.webrules.deploymanager.core.dy;

import it.webrules.deploymanager.core.utils.BasicAuth;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HTTPConn implements it.webrules.deploymanager.core.HTTPConnection {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final String username;
	private final String password;
	private final String root;

	public HTTPConn(String root, String username, String password) {
		this.root = root;
		this.username = username;
		this.password = password;
	}

	@Override
	public HttpURLConnection getConnection(String path) throws IOException {

		String slash = "";

		if (!root.endsWith("/"))
			slash = "/";

		URL url = new URL(root + slash + path);

		logger.trace("Getting {}.", url);

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		BasicAuth.setBasicAuth(connection, username, password);
		return connection;
	}

	@Override
	public InputStream getRemoteFile(String path) throws IOException {
		return (InputStream) getConnection(path).getContent();
	}

}
